package cn.edu.njpi.service.impl;

import cn.edu.njpi.mapper.TCollageMapper;
import cn.edu.njpi.mapper.TSchoolMapper;
import cn.edu.njpi.model.TCollage;
import cn.edu.njpi.model.TSchool;
import cn.edu.njpi.service.TCollageService;
import cn.edu.njpi.utils.T;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;

/**
 * @author 朱宗辉
 * @version V1.0
 * @Package cn.edu.njpi.service.impl
 * @date 2022/4/20 4:42 PM
 */
@Service
public class TCollageServiceImpl implements TCollageService {
    @Autowired
    private TCollageMapper tCollageMapper;
    @Autowired
    private TSchoolMapper tSchoolMapper;

    @Override
    public List<TCollage> getAllCollage() {
        List<TCollage> allCollage = tCollageMapper.getAllCollage();
        allCollage.sort(Comparator.comparingInt(TCollage::getSchoolId));
        for (TCollage tCollage : allCollage) {
            TSchool tSchool = tSchoolMapper.selectByPrimaryKey(tCollage.getSchoolId());
            tCollage.setSchoolName(tSchool.getSchoolName());
        }
        return allCollage;
    }

    @Override
    public List<TCollage> selectCollageBySchoolId(Integer schoolId) {
        List<TCollage> collageList = tCollageMapper.selectByStudentId(schoolId);
        collageList.sort(Comparator.comparingInt(TCollage::getCollageId));
        for (TCollage tCollage : collageList) {
            TSchool tSchool = tSchoolMapper.selectByPrimaryKey(tCollage.getSchoolId());
            tCollage.setSchoolName(tSchool.getSchoolName());
        }
        return collageList;
    }

    @Override
    public T addCollage(TCollage tCollage) {
        T t = new T();
        TCollage tCollage1 = tCollageMapper.selectByStudentIdAndCollageName(tCollage);
        if (tCollage1 == null) {
            tCollageMapper.insertSelective(tCollage);
            t.setStatus(200);
        } else {
            t.add("error", "该院系已存在");
            t.setStatus(503);
        }
        return t;
    }

    @Override
    public T changeCollage(TCollage tCollage) {
        T t = new T();
        TCollage tCollage1 = tCollageMapper.selectByPrimaryKey(tCollage.getCollageId());
        if (tCollage1 != null) {
            TCollage tCollage2 = tCollageMapper.selectByStudentIdAndCollageName(tCollage);
            if (tCollage2 == null) {
                tCollage1.setCollageName(tCollage.getCollageName());
                tCollageMapper.updateByPrimaryKeySelective(tCollage1);
                t.setStatus(200);
            } else {
                t.add("error", "该院系已存在");
                t.setStatus(503);
            }
        } else {
            t.add("error", "该院系不存在");
            t.setStatus(503);
        }
        return t;
    }

    @Override
    public TCollage selectCollageByCollageId(Integer collageId) {
        return tCollageMapper.selectByPrimaryKey(collageId);
    }
}
